
#include <fstream>
#include <iostream>

#include "boost/filesystem.hpp"

#include "FsProfileManager.h"

namespace fs = boost::filesystem;
using namespace fs;


FsProfileManager::FsProfileManager(const string& strConfigFile): ProfileManager(strConfigFile)
{
    if ( configration.find(CONFIG_PROFILE_DIR) != configration.end() )
    {
        strProfileDir = configration[CONFIG_PROFILE_DIR];

        if (!strProfileDir.empty() && strProfileDir.at( strProfileDir.length() - 1) != '/')
            strProfileDir += '/';
    }
}

Profiles
FsProfileManager::getProfiles()
{
    Profiles profiles;

    if ( fs::exists(strProfileDir) )
    {
        fs::directory_iterator itorDir;
        for (fs::directory_iterator itr(strProfileDir); itr != itorDir; ++itr)
        {
            if ( !fs::is_directory( itr->status() ) )
            {
                profiles.push_back( itr->leaf() );
            }
        }
    }

    return profiles;
}


string
FsProfileManager::Read(const string& strFilePath)
{
    string strLine;
    ifstream inFile( strFilePath.c_str() );

    while ( getline(inFile, strLine) )
    {
        if (strLine.find(RDT_CMD) == 0)
        {
            return strLine;
        }
    }

    return "";
}


Arguments
FsProfileManager::getArguments(string& strProfileName)
{
    Arguments arguments;
    string strCmd = Read(strProfileDir + strProfileName);

    if ( !strCmd.empty() )
    {
        strCmd = strCmd.substr( RDT_CMD.length() );
        ReplaceAll(strCmd, "([\\s\\t]+)", " ");

        vector<string> args = split(strCmd, " ");

        char key = RDT_PARAM_SERVER;
        vector<string>::const_iterator it;
        for (it = args.begin(); it != args.end(); it++)
        {
            string strArg = *it;
            if (strArg.find('-') == 0)
            {
                if (strArg.length() == 2)
                {
                    key = strArg.at(1);
                    arguments[key] = "";
                }
            }
            else
            {
                arguments[key] = strArg;
                key = RDT_PARAM_SERVER;
            }
        }
    }

    return arguments;
}


bool
FsProfileManager::setProfile(string& strProfileName, Arguments& arguments)
{
    string strText = "#!/bin/bash\n";
    strText.append( getCommandLine(arguments) );

    return writeFile(strProfileDir + strProfileName, strText);
}
